import 'package:get/get.dart';
import '../../../../service/HttpsClient.dart';
import 'package:flutter/material.dart';
import '../../../../utils/storage/storage.dart';
import '../../../user/controllers/user_controller.dart';
import '../../../cart/controllers/cart_controller.dart';

class PassLoginController extends GetxController {
  //TODO: Implement PassLoginController
  final HttpsClient httpsClient = HttpsClient();
  UserController userController = Get.find<UserController>();
  CartController cartController = Get.find<CartController>();
  TextEditingController usernameController = TextEditingController();
  TextEditingController passwordController = TextEditingController();

  // 去登录
  Future goLogin() async {
    String username = usernameController.text;
    String password = passwordController.text;
    // 调接口前校验
    if (username.isEmpty || password.isEmpty) {
      Get.snackbar('提示', '用户名或密码不能为空');
      return;
    }
    if (username.length < 6 || password.length < 6) {
      Get.snackbar('提示', '用户名或密码长度不能小于6位');
      return;
    }
    if (username.length < 11 && !GetUtils.isPhoneNumber(username)) {
      Get.snackbar('提示', '请输入正确的手机号');
    }
    // 调接口
    var response = await httpsClient.post(
      'api/doLogin',
      data: {'username': username, 'password': password},
    );
    print(response);
    if (response != null) {
      if (response['success'] == true) {
        Storage.setData("userinfo", response['userinfo']); // 登录成功后保存用户信息
        // Get.offAllNamed("/tabs", arguments: {"index": 4}); // 登录成功后跳转到用户首页
        Get.back();
        return;
      }
      Get.snackbar('提示', response['message']);
    } else {
      Get.snackbar('提示', '网络错误');
    }
  }

  

  @override
  void onInit() {
    super.onInit();
  }

  

  @override
  void onClose() {
    super.onClose();
    userController.getUserinfo();
  }
}
